#此示例将进化一个简单的函数以最小化其返回值。
import asyncio
import sys
import os

# 将根目录添加到 Python 路径
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))

from nano_alpha_evolve.alpha_evolve import AlphaEvolve
from nano_alpha_evolve.program_db import ProgramDB
from nano_alpha_evolve.llm_client import LLMClient
from nano_alpha_evolve.prompt_sampler import PromptSampler
from nano_alpha_evolve.evaluator import Evaluator
from nano_alpha_evolve.utils import load_program, save_program

async def main():
    """
    运行 simple_function 示例的主函数。
    """
    # 配置
    initial_program_file = os.path.join(os.path.dirname(__file__), "initial_program.py")
    evaluation_module = "examples.simple_function.evaluate"
    population_size = 5
    num_iterations = 10

    # 初始化组件时，指定 optimization_mode='min'
    program_db = ProgramDB(population_size=population_size, optimization_mode='min')
    llm_client = LLMClient()
    prompt_sampler = PromptSampler()
    evaluator = Evaluator(evaluation_module)

    # 加载初始程序
    initial_program = load_program(initial_program_file)
    initial_score = await evaluator.evaluate(initial_program)
    if initial_score:
        program_db.add_program(initial_program, initial_score)
        print(f"初始程序已加载，分数为: {initial_score['main_score']}")
    else:
        print("评估初始程序失败。")
        return

    # 创建并运行 AlphaEvolve Agent
    alpha_evolve = AlphaEvolve(
        program_db=program_db,
        llm_client=llm_client,
        prompt_sampler=prompt_sampler,
        evaluator=evaluator,
        num_iterations=num_iterations
    )

    best_program, best_score = await alpha_evolve.run()

    # 保存最佳程序
    best_program_file = os.path.join(os.path.dirname(__file__), "best_program.py")
    save_program(best_program, best_program_file)
    print(f"\n最佳程序已保存至 {best_program_file}，分数为: {best_score['main_score']}")

if __name__ == "__main__":
    asyncio.run(main())